package com.algrithom.find;

import java.util.Arrays;

/**
 * 二分查找
 *
 * @author think
 * @version 1.0.0
 * @since 2019/12/22
 */
public class BinarySearch {
    
    /**
     * @param args
     */
    public static void main(String[] args){
        int[] array = {1,7,3,8,9,2};
        int key = 8;
        Arrays.sort(array);
        System.out.println(Arrays.toString(array));
        System.out.println(bsFunc(array,key));
        System.out.println(search(array,key,0,array.length - 1));
    }
    
    /**
     * 非递归方式查找
     *
     * @param array 输入数组
     * @param key 查找关键字
     * @return 找到的序号
     */
    private static int bsFunc(int[] array,int key){
        int low = 0;
        int high = array.length - 1;
        int mid = 0;
        while (low < high) {
            mid = (low + high) / 2;
            if (array[mid] < key) {
                low = mid + 1;
            } else if (array[mid] > key) {
                high = mid - 1;
            } else {
                break;
            }
        }
        return mid;
    }
    
    /**
     * 递归方式二分查找
     *
     * @param arr 输入数组
     * @param value 查找关键字
     * @param min 最小值
     * @param max 最大值
     * @return 找到的序号
     */
    private static int search(int[] arr,int value,int min,int max){
        int mid = (min + max) / 2;
        if (value < arr[min] || value > arr[max] || min > max) {
            return -1;
        }
        if (arr[mid] < value) {
            return search(arr,value,mid + 1,max);
        } else if (arr[mid] > value) {
            return search(arr,value,min,mid - 1);
        } else {
            return mid;
        }
    }
    
    // 35. 搜索插入位置
    public int searchInsert(int[] nums,int target){
        int len = nums.length;
        int left = 0;
        int right = len - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return right + 1;
    }
}
